var superagent = require("superagent");
var cheerio = require("cheerio");
var https = require("https");
var fs = require("fs");
var url = require("url");
var querystring = require("querystring");
var util = require("util");

var targetUrl = "https://www.zhihu.com";

function index(req, res){
    var data = req.query;
    console.log(data);
    superagent.get(targetUrl + "/search?type=people&" + querystring.stringify({ q : data.q })).end(function(err, sres){
        var items = cheerioQuery(sres.text);
        
        console.log(util.inspect(items, true, null, true));
        // download image`
        var imgDownProm = [];

        for (var i = 0; i < items.message.length; i++) {
            var elem = items.message[i];
            
            imgDownProm.push(imgDownload(elem.img));
        }

        Promise.all(imgDownProm).then(function(dataArr){
            for (var i = 0; i < dataArr.length; i++) {
                var elem = dataArr[i];
                items.message[i].img = elem;
            }

            res.render("site/index", items, function(err, html){
                res.send(html);
            })
        });

        // res.render("site/index", items, function(err, html){
        //     res.send(html);
        // });
    });
}

exports.index = index;

function exit(req, res){

    fs.readdir("./Public/img/", function(err, files){
        if(err){
            console.log(err.stack);
        }

        for(let index in files){
            fs.unlink("./Public/img/" + files[index], function(err){
                if(err){
                    console.log("Delete file [failed] : " + files[index] + " : " + err.stack);
                }

                console.log("Delete file [success] : " + files[index]);
            });            
        }

        res.redirect("/");
    });

}

exports.exit = exit;

function cheerioQuery(data){
    var $ = cheerio.load(data);
    var items = {
        message : []
    }

    $(".zu-main-content .zu-main-content-inner ul.list li").each(function(index, elem){
        var $li = $(elem);

        // left content
        var $leftCon = $($li.find(".left"));

        var href = $leftCon.children("a").attr("href");
        var img = $leftCon.find("a img").attr("src");
        // img = imgDownload(img);

        var $firstChild = $leftCon.find(".body").children().eq(0);
        var name = $firstChild.children("a").text().trim();
        var sex = $firstChild.children("i").attr("title") == "他" ? "♂" : "♀";

        var intro = $leftCon.find(".body").children().eq(1).text();

        // todo right content
        var $rightCon = $($li.find(".extra"));

        var aArr = $rightCon.find("a");

        var extra = {
            answerHref : aArr.eq(0).attr("href"),
            answerNum : aArr.eq(0).children("strong").text().trim(),
            postsHref : aArr.eq(1).attr("href"),
            postsNum : aArr.eq(1).children("strong").text().trim(),
            followersHref : aArr.eq(2).attr("href"),
            followersNum : aArr.eq(2).children("strong").text().trim()
        }

        var people = {
            href : href,
            img : img,
            name : name,
            sex : sex,
            intro : intro,
            extra : extra
        }

        items.message.push(people);
    });

    return items;
}

function imgDownload(imgUrl){
    return new Promise(function(resolve, reject){

        var imgName = url.parse(imgUrl).pathname.split("/").pop();

        https.get(imgUrl)

        https.get(imgUrl, function(res){
            var imgData = "";

            res.setEncoding("binary");

            res.on("data", function(chunk){
                imgData += chunk;
            });

            res.on("end", function(err){

                var newName = new Date().getTime();
                fs.writeFile("./public/img/" + imgName, imgData, "binary", function(err){
                    if(err){
                        console.log("Download file [failed] : " + imgUrl + " : " + err.stack);
                    }else{
                        console.log("Download file [success] : " + imgUrl);
                        resolve(imgName);
                    }
                });
            });
        });

    });
}